import router from "@/router"
import { useUserStoreHook } from "@/store/modules/user"
import { usePermissionStoreHook } from "@/store/modules/permission"
import { ElMessage } from "element-plus"
import { whiteList } from "@/config/white-list"
import { getToken } from "@/utils/cache/cookies"
import asyncRouteSettings from "@/config/async-route"
import NProgress from "nprogress"
import "nprogress/nprogress.css"
import { getBanDataApi } from "@/api/role"
// import { getwebqueryState } from "@/api/webSet/order"
let banRes: any = {}
NProgress.configure({ showSpinner: false })

const fetchUserData = async (userStore: any) => {
  const [res3]: any = await Promise.all([getBanDataApi({ page: 1, size: 1 })])
  banRes = res3
  console.log(userStore)
  console.log("banRes", banRes)
}

router.beforeEach(async (to: any, _from, next) => {
  NProgress.start()
  const userStore = useUserStoreHook()
  const permissionStore = usePermissionStoreHook()

  // 设置页面标题
  if (to.meta.title) {
    document.title = `凡思特管理后台-${to.meta.title}`
    const webUrl = window.location.hostname
    if (webUrl === "www.haokasite.cn" || webUrl === "haokasite.cn") {
      document.title = `杭州云合互联网络科技有限公司`
    } else if (webUrl === "www.speedflash.cn" || webUrl === "speedflash.cn") {
      document.title = `云合互联`
    } else if (
      webUrl === "www.jiachengtongxin.cn" ||
      webUrl === "jiachengtongxin.cn" ||
      webUrl === "jcsmvip.top" ||
      webUrl === "www.jcsmvip.top"
    ) {
      document.title = `焦作嘉诚商贸有限公司`
    }
  } else {
    document.title = ""
  }

  if (getToken()) {
    // console.log("banRes", banRes)
    if (banRes.code === 200 && banRes.data.roleList[0]?.powerList.split(",").includes(to.name)) {
      NProgress.done()
      return next("/403")
    }

    if (to.path === "/login") {
      NProgress.done()
      return next({ path: "/" })
    }

    if (userStore.roles.length === 0) {
      try {
        if (asyncRouteSettings.open) {
          await userStore.getInfo()
          permissionStore.setRoutes(userStore.roles)
        } else {
          userStore.setRoles(asyncRouteSettings.defaultRoles)
          permissionStore.setRoutes(asyncRouteSettings.defaultRoles)
        }
        const existingRoutes = router.getRoutes().map((r) => r.path)
        permissionStore.dynamicRoutes.forEach((route) => {
          if (!existingRoutes.includes(route.path)) {
            router.addRoute(route)
          }
        })
        NProgress.done()
        return next({ ...to, replace: true })
      } catch (err: any) {
        userStore.resetToken()
        ElMessage.error(err.message || "路由守卫过程发生错误")
        NProgress.done()
        return next("/login")
      }
    }

    await fetchUserData(userStore) // 只在必要时调用
    NProgress.done()
    return next()
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      NProgress.done()
      return next()
    }
    NProgress.done()
    return next("/login")
  }
})

router.afterEach(() => {
  NProgress.done()
})
